﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

using Kooboo.Web.Url;
using Kooboo.CMS.Sites.Models;
using Kooboo.CMS.Sites.View;
using Kooboo.CMS.Sites.Web;

namespace Kooboo.CMS.Toolkit
{
    public class PageUtility
    {
        private const string Slash = "/";

        public static string PrependSlash(string url)
        {
            if(!url.StartsWith(Slash))
            {
                url = Slash + url;
            }
            return url;
        }

        public static string AppendSlash(string url)
        {
            return VirtualPathUtility.AppendTrailingSlash(url);
        }

        public static FrontHttpRequestWrapper Request
        {
            get
            {
                return Page_Context.Current.PageRequestContext.ControllerContext.RequestContext.HttpContext.Request as FrontHttpRequestWrapper;
            }
        }

        public static Page CurrentPage
        {
            get
            {
                return Page_Context.Current.PageRequestContext.Page;
            }
        }

        public static string CurrentPageUrl
        {
            get
            {
                string currentPageUrl = Request.RequestUrl;
                return PrependSlash(currentPageUrl);
            }
        }

        #region Absolute page url

        public static string GetAbsolutePageUrl()
        {
            return GetAbsolutePageUrl(CurrentPageUrl);
        }

        public static string GetAbsolutePageUrl(string pageUrl)
        {
            return GetAbsolutePageUrl(Site.Current, pageUrl);
        }

        public static string GetAbsolutePageUrl(Site site, string pageUrl)
        {
            FrontRequestChannel requestChannel = site.FrontRequestChannel();
            string wrapperPageUrl = FrontUrlHelper.WrapperUrl(pageUrl, site, requestChannel).ToString();
            if(requestChannel == FrontRequestChannel.Host || requestChannel == FrontRequestChannel.HostNPath)
            {
                return Request.ToAbsoluteUrl(site.Domains.First(), wrapperPageUrl);
            }
            else
            {
                return Request.ToAbsoluteUrl(wrapperPageUrl);
            }
        }

        #endregion
    }
}